import { getDetailUserInfoApi, getInfoApi, loginApi } from '@/api/user'

import { setToken, getToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
export default {
  // 开启模块化
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    setToken(state, data) {
      state.token = data

      // 存入cookie实现持久化
      setToken(data)
      console.log(data)
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    // 设置用户资料
    setUserInfo(state, data) {
      state.userInfo = data
    },
    removeUserInfo(state, data) {
      state.userInfo = {}
    }
  },
  actions: {
    async loginAction(context, data) {
      const res = await loginApi(data)
      // console.log(data)
      context.commit('setToken', res)
    },
    async getUserInfoAction(context) {
      const res = await getInfoApi()
      // console.log(res)
      const res2 = await getDetailUserInfoApi(res.userId)
      // console.log(res2)
      context.commit('setUserInfo', { ...res, ...res2 })
      return res
    },
    async quitAction(context) {
      context.commit('removeToken')
      context.commit('removeUserInfo')
      resetRouter()
      // 重置侧边栏菜单
      // 疑问？？？ user.js 和 permission.js
      // context.commit('permission/setRoutes',[])
      context.commit('permissions/setRoutes', [], { root: true })
    }
  }
}
